package com.powernode.interceptor;

import com.powernode.common.Constants;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 进入controller之前调用的方法
     * true:放行
     * false 拦截
     * @param request  请求对象
     * @param response 响应对象
     * @param handler  要访问的Controller对象
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute(Constants.SESSION_USER_KEY);
        if(null != user) {
            return true;
        }else {
            response.sendRedirect(request.getContextPath()+"/index.jsp");
            return false;
        }
    }

    /**
     * 在自己写的Controller里面的方法执行完成之后，进行视图解析之前调用的方法
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 要执行的控制器对象
     * @param modelAndView  控制器渲染视图的模型和数据对象
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     *  请求完成。数据渲染完成之后调用的方法
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
